﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Filters;
using System.Web.Http;
using System.Web.Http.Controllers;
using Logistics.Model;
using KD.Service.HR.Utility;
using System.Net.Http;
using Newtonsoft.Json;
using System.Net;
using Logistics.Utility;
using Logistics.Service;

namespace Logistics.WebApi.Attributes
{
    public class MyAuthorityAttribute : AuthorizeAttribute
    {
        private const string token = "token";
        private static string loginHeader = LogisticsConst.LOGIN_HEADER;
        public static bool loginbz=true;

        public override void OnAuthorization(HttpActionContext context)
        {
            base.OnAuthorization(context);
        }

        protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var user_token = HttpContext.Current.Request.QueryString[token];
            var accountId = CheckToken(user_token);
            //var accountId = 1;
            if (!string.IsNullOrEmpty(user_token) && accountId > 0)
            {
                HttpContext.Current.Request.Headers.Add(loginHeader, accountId.ToString());
                return true;
            }
            return false;
        }

        //权限为false执行内容
        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
         
            ResponseModel model = new ResponseModel();
            model.InitResultState(LoginEnum.Error04);
            base.HandleUnauthorizedRequest(actionContext);
            actionContext.Response.StatusCode = HttpStatusCode.OK;
            actionContext.Response.Content=new StringContent(JsonConvert.SerializeObject(model));
           
        }

        /// <summary>
        /// 验证用户凭证
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static int CheckToken(string token)
        {
            AccountService service = new AccountService(); wuliu_account_base mod = new wuliu_account_base();
            try
            {
                mod = (wuliu_account_base)CacheManager.GetTokenValue(token);
                if (mod == null)
                {
                    var model = service.IsCheckUserToken(token, DateConvert.DateTimeToStamp(DateTime.Now));
                    
                    return model.account_id.ToInt32(0);
                }

                else
                    return mod.account_id;
            }
           catch(Exception ex)
            {
                var model = service.IsCheckUserToken(token, DateConvert.DateTimeToStamp(DateTime.Now));
                if (model.IsNull())
                {
                    return 0;

                }
                return model.account_id.ToInt32(0);
            }
            
        }
    }
}